package cn.meye11.crm.service;

import cn.meye11.crm.common.DateUtils;
import cn.meye11.crm.common.RestResponse;
import cn.meye11.crm.common.StringUtils;
import cn.meye11.crm.domain.entity.ConsumptionTimesEntity;
import cn.meye11.crm.domain.entity.MemberEntity;
import cn.meye11.crm.domain.entity.RechargeTimesEntity;
import cn.meye11.crm.domain.model.ConsumptionTimes;
import cn.meye11.crm.domain.query.ConsumptionTimesQuery;
import cn.meye11.crm.mapper.ConsumptionTimesMapper;
import cn.meye11.crm.mapper.MemberMapper;
import cn.meye11.crm.mapper.RechargeTimesMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 计次消费表(ConsumptionTimes)表服务实现类
 * 默认CRUD操作
 *
 * @author makejava
 * @since 2023-12-09 20:21:07
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ConsumptionTimesService {

    private final ConsumptionTimesMapper consumptionTimesMapper;
    private final MemberMapper memberMapper;
    private final RechargeTimesMapper rechargeTimesMapper;

    private final ApplicationEventPublisher applicationEventPublisher;
    // 代码写到此区域


    /************************************* 请在上方编写新代码 **************************************/
    // 此区域为自动生成的通用代码 尽量不直接修改
    @Transactional(rollbackFor = Exception.class)
    public Long save(ConsumptionTimes model) {
        if (StringUtils.isNotBlank(model.getOperators())) {
            model.setCreatedBy(model.getOperators());
            model.setModifiedBy(model.getOperators());
        } else {
            model.setCreatedBy("Genkai");
            model.setModifiedBy("Genkai");
        }

        if (StringUtils.isBlank(model.getCreatedBy())) {
            throw new RuntimeException("创建人不能为空");
        }
        if (model.getId() != null) {
            throw new RuntimeException("主键id不可自定义");
        }
        if (model.getVersion() != null) {
            throw new RuntimeException("数据版本号不可自定义");
        }
        if (model.getTime() != null) {
            throw new RuntimeException("数据创建时间不可自定义");
        }
        if (model.getLast() != null) {
            throw new RuntimeException("数据修改时间不可自定义");
        }

        /* 重要： 计次消费后，需要更新计次充值记录中的剩余次数和已使用次数 */
        if(Objects.isNull(model.getRechargeId())){
            throw new RuntimeException("请选择需要扣减次数的充次记录!");
        }
        RechargeTimesEntity timesEntity = rechargeTimesMapper.selectByPrimaryKey(model.getRechargeId());
        if (ObjectUtils.isEmpty(timesEntity)) {
            throw new RuntimeException("未查询到对应充次记录，无法进行计次消费!");
        }
        //剩余可用次数
        int rechargeTimes = timesEntity.getRemainingTimes() == null? 0 : timesEntity.getRemainingTimes();
        if (rechargeTimes < model.getTimes()) {
            throw new RuntimeException("剩余次数不足，无法进行消费!\n 【"+timesEntity.getActivityName()+"】活动充值次数为：【" + rechargeTimes + "】次");
        }
        timesEntity.setId(model.getRechargeId());
        timesEntity.setRemainingTimes(rechargeTimes - model.getTimes());
        timesEntity.setUsedTimes(timesEntity.getUsedTimes() == null? 0 : timesEntity.getUsedTimes() + model.getTimes());
        timesEntity.setModifiedBy(model.getCreatedBy());
        rechargeTimesMapper.updateByPrimaryKeySelective(timesEntity);

        /* 重要： 计次消费完成后，需要更新会员表中的账户充值次数 */
        MemberEntity member = memberMapper.selectByPrimaryKey(model.getMemberId());
        if (ObjectUtils.isEmpty(member)) {
            throw new RuntimeException("会员信息不存在，无法进行计次消费!");
        }

        // 判断账户余额是否足够消费
        if (Objects.isNull(member.getTimes()) || member.getTimes() == 0) {
            throw new RuntimeException("账户充值次数不足，无法进行消费!\n 当前账户充值次数为：【0】次");
        }
        int remainingTimes = member.getTimes();
        if (remainingTimes < model.getTimes()) {
            throw new RuntimeException("账户充值次数不足，无法进行消费!\n 当前账户充值次数为：【" + remainingTimes + "】次");
        }
        member.setId(model.getMemberId());
        member.setTimes(remainingTimes - model.getTimes());
        member.setModifiedBy(model.getCreatedBy());
        memberMapper.updateByPrimaryKeySelective(member);


        ConsumptionTimesEntity entity = new ConsumptionTimesEntity(model);
        entity.setTime(DateUtils.toLocalDateTime(new Date()));
        entity.setLast(DateUtils.toLocalDateTime(new Date()));
        entity.setConsumptionTime(DateUtils.toLocalDateTime(new Date()));
        entity.setActivityName(timesEntity.getActivityName());
        consumptionTimesMapper.insertSelective(entity);
        return entity.getId();
    }

    public void remove(ConsumptionTimes model) {

        if (model.getId() == null) {
            throw new RuntimeException("ID不能为空");
        }

        if (StringUtils.isBlank(model.getModifiedBy())) {
            throw new RuntimeException("修改人不能为空");
        }

        ConsumptionTimesEntity entity = consumptionTimesMapper.selectByPrimaryKey(model.getId());
        if (entity == null) {
            throw new RuntimeException("ID:" + model.getId() + "不存在");
        }
        consumptionTimesMapper.deleteByPrimaryKey(model.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ConsumptionTimes model) {

        if (model.getId() == null) {
            throw new RuntimeException("ID不能为空");
        }

        if (StringUtils.isBlank(model.getModifiedBy())) {
            throw new RuntimeException("修改人不能为空");
        }

        ConsumptionTimesEntity entity = consumptionTimesMapper.selectByPrimaryKey(model.getId());
        if (entity == null) {
            throw new RuntimeException("ID:" + model.getId() + "不存在");
        }

        ConsumptionTimesEntity save = new ConsumptionTimesEntity(model);
        save.setLast(LocalDateTime.now());
        save.setTime(entity.getTime());
        consumptionTimesMapper.updateByPrimaryKey(save);
    }

    public ConsumptionTimes get(Long id) {
        ConsumptionTimesEntity entity = consumptionTimesMapper.selectByPrimaryKey(id);
        return entity == null ? null : new ConsumptionTimes(entity);
    }

    public Long count(ConsumptionTimesQuery query) {
        return consumptionTimesMapper.count(query);
    }

    public RestResponse<List<ConsumptionTimes>> list(ConsumptionTimesQuery query) {
        // 单次查不得大于32767条数据，否则需要分页
        query.setLimit((int) Short.MAX_VALUE);
        return page(query);
    }

    public RestResponse<List<ConsumptionTimes>> page(ConsumptionTimesQuery query) {
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<ConsumptionTimesEntity> list = consumptionTimesMapper.list(query);
        PageInfo<ConsumptionTimesEntity> count = new PageInfo<>(list);
        List<ConsumptionTimes> collect = list.stream().map(ConsumptionTimes::new).collect(Collectors.toList());
        return RestResponse.success(count.getTotal(), collect);
    }
}
